<template>
    <fieldset>
        <legend>产品列表</legend>
        <ul>
            <li v-for="item in productData" :key="item.id">
                <b>
                   产品名字：{{item.title}}
                </b>
                -------
                <b>
                    价格：{{item.price}}
                </b>
                -------
                <b>
                    库存：{{item.inventory}}
                </b>
                -------
                <button @click="addCart(item)" :disabled="item.inventory===0">添加到购物车</button>
            </li>
        </ul>
    </fieldset>
</template>
<script setup>
    // 直接引入store就可以
    import {useUser} from "../../store/users"
    import { cartCart } from "../../store/cart";
    // 解构state,会丢失数据的响应性，使用storeToRefs来保持响应性
    import {storeToRefs} from "pinia"
    let Data = useUser()
    let data = cartCart()
    // 解构数据
    let {productData} = storeToRefs(Data)
    let {cartData} = storeToRefs(data)
    Data.fetchData()
    let addCart = (item) => {
        item.inventory--
        let target = cartData.value.find(a=>a.id === item.id)
        if(!target){
            let obj = {
                    title: item.title,
                    price: item.price,
                    count: 1,
                    id: item.id
                }
            cartData.value.push(obj)
        }else{
            target.count++
        }
    }
</script>